<template>
	<view>
    <AuthButton :needRefresh="needRefreshAuthBtn" @successAuth="successAuthHandler">
      <view slot="content" class="username-wrapper">
        <image :src="userDetail.avatar || '/static/my/defaultAvatar.png'" class="userAvatar"></image>
        <view class="right-area">
          <text class="user-name">{{ userDetail.nickName || "点击登录" }}</text>
          <image @click="goRenzhengSuccessHandler" src="https://zuwuzuwebs.oss-cn-beijing.aliyuncs.com/jianbanMini/my/%E5%B7%B2%E8%AE%A4%E8%AF%81%402x%20%281%29.png" :class="{'renzhengIcon': true, 'hide': !isRenZheng}"></image>
          <view @click="goRenzhengHandler" :class="{'renzhengBtn': true, 'hide': isRenZheng}">
            实名认证
            <image class="backIcon" src="https://zuwuzuwebs.oss-cn-beijing.aliyuncs.com/jianbanMini/my/%E8%BF%94%E5%9B%9E%20%281%29%402x%20%281%29%20%281%29.png"></image>
          </view>
        </view>
      </view>
    </AuthButton>

    <view class="content-container">
      <!-- 我的订单模块 -->
      <AuthButton :needRefresh="needRefreshAuthBtn" @successAuth="successAuthHandler">
        <view slot="content" class="unit order-wrapper">
          <view class="top-area">
            <text>我的订单</text>
            <view class="see-all-cls" @click="seeAllOrderHandler">
              <text class="span2">查看全部</text>
              <image class="arrow" src="../../static/my/jiantou.png"></image>
            </view>
          </view>
          <view class="icon-wrapper">
            <view
              v-for="(menuObj, idx) in orderMenus"
              :key="idx"
              :class="{ 'icon-unit': true, nomr: idx > 0 && (idx + 1) % 4 == 0 }"
              @click="clickOrderMenu(menuObj)"
            >
              <image :src="menuObj.fileUrl" class="icon"></image>
              <text v-if="menuObj.showNum && checkHasUserinfo" class="bubble">{{ menuObj.showNum }}</text>
              <text class="text">{{ menuObj.describeInfo }}</text>
            </view>
          </view>
        </view>
      </AuthButton>
      <ad
          unit-id="ad_tiny_2021002193643103_202207112200038236"
      />

      <!-- 我的服务模块 -->

        <view slot="content" class="unit service-wrapper">
          <view class="top-area">我的服务</view>
          <view class="icon-wrapper">
            <view
              :class="{ 'icon-unit': true, nomr: idx > 0 && (idx + 1) % 4 == 0 }"
              v-for="(menuObj, idx) in serviceMenus"
              :key="idx"
              @click="clickServiceHandler(menuObj)"
            >
              <view v-if="isAuthService(menuObj)">
                <image :src="menuObj.fileUrl" class="icon"></image>
                <text v-if="menuObj.showNum" class="bubble">{{ menuObj.showNum }}</text>
                <text class="text">{{ menuObj.describeInfo }}</text>
              </view>
              <view v-else>
                <AuthButton :needRefresh="needRefreshAuthBtn" @successAuth="successAuthHandler">
                  <view slot="content" >
                    <image :src="menuObj.fileUrl" class="icon"></image>
                    <text v-if="menuObj.showNum" class="bubble">{{ menuObj.showNum }}</text>
                    <text class="text">{{ menuObj.describeInfo }}</text>
                  </view>
                </AuthButton>
              </view>

            </view>
          </view>
        </view>


      <view class="title-area">
        <view class="round round1"></view>
        <view class="round round2"></view>
        <view class="round round3"></view>
        <text class="title">更多热销商品</text>
        <view class="round round4"></view>
        <view class="round round5"></view>
        <view class="round round6"></view>
      </view>

      <view class="productList-area">
        <div class="left">
          <view
            class="item"
            v-for="(productObj, idx) in productList"
            :key="idx"
          >
            <productItem productNameKey="productName" v-if="idx % 2 == 0" :productObj="productObj" :showTag="true">
              <JiangpaiSlot v-if="idx < 3" :role="returnRole(idx)" slot="topLeft" />
            </productItem>
          </view>
        </div>

        <div clas="right">
          <view
            class="item"
            v-for="(productObj, idx) in productList"
            :key="idx"
          >
            <productItem productNameKey="productName" v-if="idx % 2 == 1" :productObj="productObj" :showTag="true">
              <JiangpaiSlot v-if="idx < 3" :role="returnRole(idx)" slot="topLeft" />
            </productItem>
          </view>
        </div>
      </view>
    </view>
	</view>
</template>

<script>
// 个人中心-我的页面
import ProductItem from "../../components/productItem/productItem.vue"
import JiangpaiSlot from "../../components/productItem/slots/jiangpai.vue"
import AuthButton from "../../components/authButton/authButton.vue"
import { request, getZWZUserDetail, checkHasUserBasicInfo, checkHasShiMingRenZheng } from "@/utils"
import { ALL_ORDER_ID } from "../../utils/constant"
import { resetLocalAuth } from "../../utils/platform"

export default {
  data() {
    return {
      avatar: "",
      userName: "", // 用户名
      orderMenus: [], // 订单栏的菜单列表
      serviceMenus: [], // 我的服务栏的菜单列表
      productList: [], // 更多热销商品
      userDetail: {}, // 用户详情数据
      needRefreshAuthBtn: false, // 是否需要强制authButton组件进行刷新
      isRenZheng: false, // 表示是否已实名认证，默认没有
      idCard:"",//身份证信息
      first: true, // 第一次拉数据
      checkHasUserinfo: false,
    }
  },

  components: {
    ProductItem,
    JiangpaiSlot,
    AuthButton,
  },
  
  onLoad() {
    this.setUserDetail()
  },

  onShow() {
    this.fetchConfigureDataHandler()
    this.fetchShimingRenZhengStatus()
    // 页面显示时判断一下用户是否有解除授权，不放到onLoad的原因是为了避免解除授权之后在回到小程序还是显示头像
    // 这样做的代价就是每次显示都得执行，花费大概3ms左右
    const sucCb = () => {
      this.needRefreshAuthBtn = !this.needRefreshAuthBtn
      this.isRenZheng = false // 取消授权后，将认证状态清一下
      this.setUserDetail()
    }
    // 无论如何resetLocalAuth都是会调用的
    if (this.first) {
      const cb = () => {
        this.first = false
        resetLocalAuth(sucCb) // 注：该方法只是删了本地的头像以及昵称，但其实这些信息还是保留在租物租服务器的
      }
      this.fetchShimingRenZhengStatus(cb) // 之所以resetLocalAuth需要在加载到接口返回数据之前执行，是因为需要解决这种问题：用户在租物租已经实名认证过，但是解除拉授权，那么此时打开我的页面，异步请求和onshow之间顺序不确定
    } else {
      resetLocalAuth(sucCb) // 注：该方法只是删了本地的头像以及昵称，但其实这些信息还是保留在租物租服务器的
    }
  },

  methods: {
    /**
     * 加载实名认证的状态
     */
    fetchShimingRenZhengStatus(cb) {
      checkHasShiMingRenZheng().then(obj => {
        this.idCard = obj.idCard
        this.isRenZheng = obj.checkResult
      }).catch(() => {
        this.isRenZheng = false
      }).finally(() => {
        cb && cb()
      })
    },

    /** 设置用户详细数据 */
    setUserDetail() {
      this.checkHasUserinfo = checkHasUserBasicInfo()
      this.userDetail = getZWZUserDetail()
    },

    // 监听点击去认证
    goRenzhengHandler() {
      this.stopActionWhenNoAuth().then(() => {
        this.$onTo("/pages/certificates/certificates?type=my")
      })
    },

    // 已认证的话跳转到认证成功页面
    goRenzhengSuccessHandler() {
      this.stopActionWhenNoAuth().then(() => {
        this.$onTo(`/pages/certificatesSuccess/certificatesSuccess?idCard=${this.idCard}`)
      })
    },

    /**
     * 当用户未进行授权操作时，拦截接下来的点击行为
     */
    stopActionWhenNoAuth() {
      return new Promise((resolve, reject) => {
        if (this.checkHasUserinfo) resolve()
        else reject()
      })
    },

    /**
		 * 点击订单栏各个图标的时候触发，对于订单模块来说，忽略后台所配置的跳转链接
		 */
    clickOrderMenu(menuObj={}) {
      this.stopActionWhenNoAuth().then(() => {
        const { extCode } = menuObj
        if (!extCode) {
          this.$errHandler("不存在extCode")
          return
        }
        this.$onTo(`pages/orderList/orderList?tab=${extCode}`)
      })
    },

    isAuthService(serviceItem) {
      const link = serviceItem?.link
      let noAuthUrl = ["pages/address/address"];
      return noAuthUrl.includes(link);
    },
    /**
     * 点击服务的时候触发
     */
    clickServiceHandler(serviceItem) {
      const link = serviceItem?.link
      if (!link) return
      let noAuthUrl = ["pages/address/address"];
      if (noAuthUrl.includes(link)) {
        this.$onTo(link)
      } else {
        this.stopActionWhenNoAuth().then(() => {
          this.$onTo(link)
        })
      }

    },
    
    /**
     * 加载这个页面的配置信息数据
     */
    fetchConfigureDataHandler() {
      return request("/hzsx/aliPay/index/myPage", {}, "GET", true, true).then(res => {
        const resData = res && res.data
        this.orderMenus = resData.orders || [] // 订单菜单项
        this.serviceMenus = resData.services || [] // 服务菜单项
        this.productList = resData.products || [] // 商品列表数据
      })
    },

    /**
     * 返回奖牌的种类
     */
    returnRole(idx) {
      const roleList = ["金", "银", "铜"]
      return roleList[idx]
    },

    /**
     * 查看所有订单
     */
    seeAllOrderHandler() {
      this.stopActionWhenNoAuth().then(() => {
        this.$onTo(`pages/orderList/orderList?tab=${ALL_ORDER_ID}`)
      })
    },

    /**
     * 成功登录之后的回调方法
     */
    successAuthHandler() {
      this.setUserDetail()
    }
  }
}
</script>

<style lang="scss" scoped>
.username-wrapper {
	background: #fff;
	height: 180rpx;
	display: flex;
	align-items: center;
	padding-left: 40rpx;
	border-radius: 0rpx 0rpx 20rpx 20rpx;
  .right-area {
    display: flex;
    flex-direction: column;
    .user-name {
      font-family: PingFangSC-Medium, PingFang SC;
      font-size: 36rpx;
      font-weight: 500;
      line-height: 50rpx;
      color: #333333;
      margin-bottom: 10rpx;
    }
    .renzhengIcon {
      width: 131rpx;
      height: 49rpx;
    }
    .hide {
      display: none;
    }
    .renzhengBtn {
      width: 136rpx;
      height: 40rpx;
      @include global-background-color();
      border-radius: 26rpx;
      font-size: 22rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 40rpx;
      text-align: center;
      position: relative;
      .backIcon {
        width: 10rpx;
        height: 16rpx;
        margin-left: 5rpx;
      }
    }
  }
}
.userAvatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}
.content-container {
	background: #f7f7f7;
	padding: 20rpx;
}
.unit {
	padding: 30rpx 0;
	background: #ffffff;
	border-radius: 20rpx;
  box-sizing: border-box;
  min-height: 220rpx;
	.top-area {
    height: 45rpx;
		padding: 0 30rpx;
    padding-right: 0;
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #333333;
		display: flex;
    align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
    .see-all-cls {
      border-right: 30rpx solid transparent;
      border-left: 30rpx solid transparent;
      height: 45rpx;
      line-height: 45rpx;
    }
		.span2 {
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
			margin-right: 10rpx;
		}
		.arrow {
			width: 12rpx;
			height: 18rpx;
		}
	}
	.icon-wrapper {
		padding: 0 60rpx;
		display: flex;
		flex-wrap: wrap;
		.icon-unit {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 22rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333333;
			width: 4em;
			margin-right: calc((100% - 16em) / 3);
			margin-top: 40rpx;
      position: relative;
			.icon {
				width: 58rpx;
				height: 58rpx;
				margin-bottom: 8rpx;
        display: flex;
        margin-left: 0.08rem;
			}
      .text{
        font-size: 0.22rem;
        font-family: PingFangSC-Regular,PingFang SC;
        font-weight: 400;
        display: flex;
      }
      .bubble {
        position: absolute;
        background: #1F2129;
        border-radius: 13rpx;
        border: 2rpx solid #FFFFFF;
        font-size: 16rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        @include global-color();
        padding: 0 15rpx;
        z-index: 5;
        height: 26rpx;
        line-height: 26rpx;
        top: -14rpx;
        right: -14rpx;
      }
		}
		.icon-unit:nth-child(-n + 4) {
			margin-top: 0;
		}
		.nomr {
			margin-right: 0;
		}
	}
}
.order-wrapper {
	margin-bottom: 20rpx;
}
.title-area {
	height: 90rpx;
	background: #f7f7f7;
	display: flex;
	align-items: center;
	justify-content: center;
	.round {
		border-radius: 50%;
		background: linear-gradient(180deg, #fbdc97 0%, #f69b24 100%);
		margin-right: 10px;
	}
	.round1,
	.round6 {
		width: 5rpx;
		height: 5rpx;
	}
	.round2,
	.round5 {
		width: 8rpx;
		height: 8rpx;
	}
	.round3,
	.round4 {
		width: 12rpx;
		height: 12rpx;
		margin-right: 21rpx;
	}
	.title {
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #333333;
		margin-right: 21rpx;
	}
	.round4 {
		margin-right: 10rpx;
	}
	.round6 {
		margin-right: 0;
	}
}
.productList-area {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .left, .right {
    display: flex;
    flex-direction: column;
  }
  .item {
    width: 344rpx;
  }
}
</style>
